package com.mg.framework.tiled;

import java.lang.reflect.InvocationTargetException;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;

public class TileLayer extends MapLayer {

	private TileObject[][] tileObjects;

	public TileObject[][] getTileObjects() {
		return tileObjects;
	}

	private Bitmap mapLayerBitmap;
	private Canvas canvas;

	public TileLayer(int layerWidth, int layerHeight) {
		super(layerWidth, layerHeight);
	}

	@Override
	protected void setBounds(Rectangle bounds) {
		super.setBounds(bounds);
		tileObjects = new TileObject[bounds.height][bounds.width];
	}

	public void setTileAt(int x, int y, Tile ti, String tileObjectPackageName) {
		if (bounds.contains(x, y)) {
			if (ti == null) {
				tileObjects[y - bounds.y][x - bounds.x] = null;
			} else {
				TileObject tileObject;
				try {
					tileObject = (TileObject) Class
							.forName(tileObjectPackageName + "." + ti.getType())
							.getConstructor(Tile.class, int.class, int.class)
							.newInstance(ti, y - bounds.y, x - bounds.x);
					tileObjects[y - bounds.y][x - bounds.x] = tileObject;
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}

			}
		}
	}

	public TileObject getTileObjectAt(int tx, int ty) {
		return (bounds.contains(tx, ty)) ? tileObjects[ty - bounds.y][tx
				- bounds.x] : null;
	}

	public Bitmap getMapLayerBitmap() {

		if (mapLayerBitmap == null) {
			this.mapLayerBitmap = Bitmap.createBitmap(
					bounds.width * super.map.getTileWidth(), bounds.height
							* super.map.getTileHeight(),
					Bitmap.Config.ARGB_8888);
			this.canvas = new Canvas(mapLayerBitmap);
		} else {
			this.canvas.drawColor(Color.BLACK);
		}
		Tile t = null;
		for (int i = 0; i < this.bounds.height; i++) {
			for (int j = 0; j < this.bounds.width; j++) {
				TileObject tmpTileObject = this.getTileObjectAt(i, j);
				if (tmpTileObject != null) {
					t = tmpTileObject.getTile();
//					if (t != null) {
//						this.canvas.drawBitmap(t.getTileBitmap(),
//								i * t.getWidth(), j * t.getHeight(), null);
//					}
				}
			}
		}

		return this.mapLayerBitmap;
	}

}
